package org.apache.ibatis.common.type;

import java.io.ByteArrayInputStream;
import java.sql.*;

/**
 * @Name BlogTypeHandler
 * @Description: [SQL Blob -> JAVA byte[]] 类型处理器
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-05-10 17:26:48
 **/
public class BlobTypeHandler extends BaseTypeHandler<byte[]> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, byte[] parameter, JdbcType jdbcType) throws SQLException {
        ByteArrayInputStream bis = new ByteArrayInputStream(parameter);
        ps.setBinaryStream(i, bis, parameter.length);
    }

    @Override
    public byte[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Blob blob = rs.getBlob(columnName);
        byte[] result = null;
        if (null != blob) result = blob.getBytes(1, (int) blob.length());
        return result;
    }

    @Override
    public byte[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Blob blob = rs.getBlob(columnIndex);
        byte[] result = null;
        if (null != blob) result = blob.getBytes(1, (int) blob.length());
        return result;
    }

    @Override
    public byte[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Blob blob = cs.getBlob(columnIndex);
        byte[] result = null;
        if (null != blob) result = blob.getBytes(1, (int) blob.length());
        return result;
    }
}

